/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClientPanel.java
 *
 * Created on 2011-08-13, 15:38:50
 */
package remotechessplayer;

import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author Jedrek
 */
class ClientPanel extends javax.swing.JPanel implements Runnable{

    Thread thread;
    
    SettingsPanel parent;
    Socket socket = null;
    String host = null;
    int port = -1;
    boolean connected = false;
    boolean chosen = false;
    
    /** Creates new form ClientPanel */
    public ClientPanel(SettingsPanel parent) {
        super();
        this.parent = parent;
        initComponents();
    }
    
    public void closeConnection(){
        if(socket!=null)
            synchronized(socket){
                try {
                    socket.close();
                    lState.setText("disconnected!");
                    jButton1.setText("Connect");
                    connected = false;
                    chosen = false;
                    socket = null;
                } catch (Exception ex) {
                }
            }
    }
    
    @Override
    public void run() {
        byte msg;
        while(!chosen){
            try{
                Thread.sleep(1000);
            } catch(Exception e){}
            try{
                if((msg = (byte)socket.getInputStream().read()) < 0)
                    closeConnection();
                else if(msg == RemoteChessPlayer.YOU_ARE_THE_CHOSEN_ONE){
//                    socket.getOutputStream().write(0);
                    socket.setSoTimeout(100);
                    ((RemoteChessPlayer)parent).submitConnection();
                    break;
                }
            } catch(Exception e){
                closeConnection();
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfHost = new javax.swing.JTextField();
        tfPort = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lState = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Client settings"));
        setPreferredSize(new java.awt.Dimension(200, 190));

        jLabel1.setText("Host:");

        jLabel2.setText("Port:");

        jButton1.setText("Connect");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("State:");

        lState.setText("-");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(lState, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
                    .addComponent(jLabel2)
                    .addComponent(jButton1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tfPort, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                            .addComponent(tfHost, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lState))
                .addContainerGap(44, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(!connected){
            try{
                port = Integer.parseInt(tfPort.getText());
            } catch(Exception e){
                tfPort.setText("");
            }
            try{
                host = tfHost.getText();
            } catch(Exception e){
                tfHost.setText("");
            }

            try{
                socket = new Socket(host, port);
                connected = true;
            } catch(Exception e){
            }
            if(socket.isConnected()){
                lState.setText("connected!");
                jButton1.setText("Disconnect");
                connected = true;
                new Thread(this).start();
            }
            else{
                lState.setText("disconnected!");
                jButton1.setText("Connect");
                connected = false;
            }   
        } else{
            closeConnection();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    public javax.swing.JLabel lState;
    public javax.swing.JTextField tfHost;
    public javax.swing.JTextField tfPort;
    // End of variables declaration//GEN-END:variables
}
